from selenium import webdriver
import time

from selenium.webdriver.common.by import By

"""
多窗口操作
本例已经不适合,因为现在百度点立即注册后是新的tab页
"""

driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.get("http://www.baidu.com")

# 获得百度搜索窗口句柄
search_windows = driver.current_window_handle

driver.find_element(By.LINK_TEXT, value="登录").click()
driver.find_element(By.LINK_TEXT, "立即注册").click()

# 获得当前所有打开窗口的句柄
all_handles = driver.window_handles

# 进入注册窗口
for handle in all_handles:
    if handle != search_windows:
        driver.switch_to.window(handle)
        print("now register window")
        driver.find_element(By.NAME, "account").send_keys("username")
        driver.find_element(By.NAME, "password").send_keys("password")
        time.sleep(2)

# 回到搜索窗口
for handle in all_handles:
    if handle == search_windows:
        driver.switch_to.window(handle)
        print("now search window!")
        time.sleep(2)

driver.quit()
